package com.framework.main.sys.module.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import com.framework.base.constant.ActionConstants;
import com.framework.base.constant.WebConstants;
import com.framework.base.service.BaseServiceImp;
import com.framework.base.struts.BaseVo;
import com.framework.base.util.StringUtil;
import com.framework.base.util.Struts2Utils;
import com.framework.base.util.SysConfUtil;
import com.framework.main.sys.module.dao.ModuleDao;
import com.framework.main.sys.module.dao.ModuleOperationDao;
import com.framework.main.sys.module.domain.ModuleOperationVO;
import com.framework.main.sys.module.domain.ModuleVO;

/**
 * @Description:功能描述
 * @Company: framework
 * @author：www.51wuxia.com
 * @version 1.0
 * @Date 2011-6-21 上午10:18:50
 */
public class ModuleServiceImp extends BaseServiceImp implements ModuleService {
	public static boolean isUpdateCache=false;//修改
	private ModuleOperationDao moduleOperationDao;
	private int position = 0;
	private int trCss = 0;
	public String doInsert(BaseVo vo) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		ModuleVO mvo = (ModuleVO) vo;
		List<ModuleOperationVO> moduleOperationVOList = mvo
				.getModuleOperationVOList();
		if (moduleOperationVOList != null && moduleOperationVOList.size() > 0) {
			int i = 1;
			for (ModuleOperationVO moduleOperationVO : moduleOperationVOList) {
				if (!StringUtil.isNullorEmpty(moduleOperationVO
						.getOperationIdf())) {
					moduleOperationVO.setModuleidf(mvo.getModuleIdf());
					moduleOperationVO.setDatasortNumf(i);
					moduleOperationDao.doInsert("doInsert", moduleOperationVO);// 保存操作
					i++;
				}
			}
		}
		map.put("moduleIdf", mvo.getParentIdf());
		map.put("remarkf", "");
		this.getBaseDao().doUpdate("doUpdateRemark", map);//更新父节点的remark
		this.getBaseDao().doUpdate("doUpdateDatasortNumf",
				mvo.getDatasortNumf());// 加一
		mvo.setDatasortNumf(mvo.getDatasortNumf() + 1);
		mvo.setRemarkf("3");
		this.getBaseDao().doUpdate("doInsert", vo);
		//更新application里的菜单
		Struts2Utils.getSession().getServletContext().setAttribute(WebConstants.WHOLEMENUTREE,this.toListNoPage());
		
		return ActionConstants.RELOAD;
	}
	
	/**
	 * 
	 * @Description:功能描述
	 * @author：www.51wuxia.com

	 * @Date 2012-05-09 下午03:03:17
	 */
	@SuppressWarnings("unchecked")
	public String toGetWholeModuleForSelect(StringBuilder output, String resourceID)throws Exception {
		List moduleAndOperlist = getBaseDao().queryForList("toList"," order by " + WebConstants.DEFAULTORDERFIDS);
		if (moduleAndOperlist.size() == 0) {
			ModuleVO vo = new ModuleVO();
			vo.setModuleIdf("-1");
			vo.setNamef(SysConfUtil.getBuildUnit());
			vo.setParentIdf("-2");
			vo.setRemarkf("3");
			vo.setDatasortNumf(1);
			super.doInsert(vo);
			moduleAndOperlist.add(vo);
		}
		for (int i = 0; i < moduleAndOperlist.size(); i++) {
			ModuleVO moduleVO = (ModuleVO) moduleAndOperlist.get(i);
			if (resourceID.equalsIgnoreCase(moduleVO.getParentIdf())) {
				boolean isHasChildren = isHasChildren(moduleAndOperlist,moduleVO.getModuleIdf());
				output.append("<option value=\""+moduleVO.getModuleIdf()+"\"");
				if(position==0){
					output.append(" style=\"background:#669933\" ");
				}
               if(position==1){
            	   output.append(" style=\"background:#669966\" ");
				}
               if(position==2){
            	   output.append(" style=\"background:#669999\" ");
				}
               if(position==3){
            	   output.append(" style=\"background:#cccccc\" ");
				}
				output.append(">"+echoSpace(position * 2)+moduleVO.getNamef()+"</option>\n");												
				if (isHasChildren) {
					position++;
					toGetWholeModuleForSelect(output, moduleVO.getModuleIdf());
					position--;
				}
			}
			trCss++;
		}
		return output.toString();
	}

	public String doUpdate(BaseVo vo) throws Exception {
		ModuleVO mvo = (ModuleVO) vo;
		moduleOperationDao.doDelete("doDeleteByModuleId", new String[] { mvo
				.getModuleIdf() });//删除操作

		List<ModuleOperationVO> moduleOperationVOList = mvo
				.getModuleOperationVOList();
		if (moduleOperationVOList != null && moduleOperationVOList.size() > 0) {
			int i = 1;
			for (ModuleOperationVO moduleOperationVO : moduleOperationVOList) {
				if (!StringUtil.isNullorEmpty(moduleOperationVO
						.getOperationIdf())) {
					moduleOperationVO.setModuleidf(mvo.getModuleIdf());
					moduleOperationVO.setDatasortNumf(i);
					moduleOperationDao.doInsert("doInsert", moduleOperationVO);// 保存操作
					i++;
				}
			}
		}
		ModuleVO oldMvo = (ModuleVO)this.getBaseDao().getById("toView", mvo.getModuleIdf());
		if(oldMvo!=null&&mvo!=null){
			if(oldMvo.getDatasortNumf()!=mvo.getDatasortNumf()+1){//更新了顺序
				mvo.setDatasortNumf(mvo.getDatasortNumf()+1);
				Map<String, String> map = new HashMap<String, String>();
				if(oldMvo.getDatasortNumf()>mvo.getDatasortNumf()){
					map.put("betweenB", new Long(oldMvo.getDatasortNumf()).toString());
					map.put("betweenA", new Long(mvo.getDatasortNumf()).toString());
					map.put("addOrReduce", new String("+1"));
				}else{
					map.put("betweenA", new Long(oldMvo.getDatasortNumf()).toString());
					map.put("betweenB", new Long(mvo.getDatasortNumf()).toString());
					map.put("addOrReduce", new String("-1"));
				}
				this.getBaseDao().doUpdate("doUpdateDatasortNum", map);//把将要更新的记录的顺序号对应的记录，更改为要更新记录的旧顺序号，也就是顺序号交换
			}
		}
		this.getBaseDao().doUpdate("doUpdate", mvo);//更新记录
		//更新application里的菜单
		if(isUpdateCache){
			Struts2Utils.getSession().getServletContext().setAttribute(WebConstants.WHOLEMENUTREE,this.toListNoPage());
		}
		return ActionConstants.RELOAD;
	}
	
	public String toViewModule(String resourceID,String pagePath) throws Exception{
		return toViewWholeModuleOper(new StringBuilder(1000),resourceID,pagePath);
	}
	
	/**
	 * 
	 * @Description:功能描述
	 * @author：www.51wuxia.com
	 * @Date 2011-6-22 下午03:03:17
	 */
	@SuppressWarnings("unchecked")
	public String toViewWholeModuleOper(StringBuilder output, String resourceID,String pagePath)
			throws Exception {
//		String superStr = Struts2Utils.getRequest().getParameter("super");
//		String sql = " where statusf = 0 order by " + WebConstants.DEFAULTORDERFIDS;
//		if(null!=superStr && superStr.equals("1")){
//			String sql = " where parentIdf='-1' or parentIdf = '-2' order by " + WebConstants.DEFAULTORDERFIDS;
//		}
		String sql = null;
		if(resourceID.equals("-2")){
			sql = " where parentIdf='-1' or parentIdf = '-2' order by " + WebConstants.DEFAULTORDERFIDS;
		}else{
			sql = " where parentIdf='"+resourceID+"' order by " + WebConstants.DEFAULTORDERFIDS;
		}
		List moduleAndOperlist = getBaseDao().queryForList("toList",sql);
		
		if (moduleAndOperlist.size() == 0) {
			ModuleVO vo = new ModuleVO();
			vo.setModuleIdf("-1");
			vo.setNamef(SysConfUtil.getBuildUnit());
			vo.setParentIdf("-2");
			vo.setRemarkf("3");
			vo.setDatasortNumf(1);
			super.doInsert(vo);
			//moduleAndOperlist.add(vo);
		}
		for (int i = 0; i < moduleAndOperlist.size(); i++) {
			ModuleVO moduleVO = (ModuleVO) moduleAndOperlist.get(i);
			if (resourceID.equalsIgnoreCase(moduleVO.getParentIdf())) {
				boolean isHasChildren = isHasChildren(moduleAndOperlist,
						moduleVO.getModuleIdf());
				if(resourceID.equals("-2") || resourceID.equals("-1")){
					output
					.append(
							"<tr class=\"td1\" id=\""+moduleVO.getModuleIdf()+"\">\n<td width=\"80%\" align=\"left\">\n")
					.append(echoSpace(position * 2));
				}else{
					output
					.append(
							"<tr class=\"td2\" name=\""+moduleVO.getParentIdf()+"\">\n<td width=\"80%\" align=\"left\" onmouseover=\"changeBgColorOnMouseOver(this);\" onmouseout=\"changeBgColorOnMouseOut(this);\">\n")
					.append(echoSpace(2 * 2));
				}
//				output
//				.append(
//						"<tr class=\"td"+(trCss%2+1)+"\">\n<td width=\"80%\" align=\"left\">\n")
//				.append(echoSpace(position * 2));
//				if(position==1){
//					output.append("<a name=\""+moduleVO.getModuleIdf()+"\" id=\""+moduleVO.getModuleIdf()+"\"></a>");
//				}
				output.append(
						"<input name=\"moduAndOper\" type=\"checkbox\" onclick=\"javascript:check(this);\" value=\"")
				.append(moduleVO.getModuleIdf()).append("\" ").append(
						"id=\"r").append(moduleVO.getParentIdf())
				.append("\" cid=\"r").append(moduleVO.getModuleIdf());
				if(resourceID.equals("-2")||!resourceID.equals("-1")){
					output.append("\"><b>").append(moduleVO.getNamef()).append(
					"</b>");
				}else{
					output.append("\"><b style=\"cursor: hand\" onclick=\"toViewModule('"+moduleVO.getModuleIdf()+"','"+Struts2Utils.getRequest().getContextPath()+"')\">").append(moduleVO.getNamef()).append(
						"</b>");
				}
				// Operation Begin
				List<ModuleOperationVO> oprList = moduleVO
						.getModuleOperationVOList();
				if (oprList != null && oprList.size() > 0) {
					output.append("&nbsp;");
					output.append(echoLine(5));
					output.append("&nbsp;");
					for (int j = 0; j < oprList.size(); j++) {
						ModuleOperationVO operation = (ModuleOperationVO) oprList
								.get(j);
						output
								.append(
										"<input name=\"moduAndOper\" type=\"checkbox\"")
								.append(" value=\"").append(
										operation.getOperationIdf()).append(
										"\" type=\"checkbox\" cid=\"o").append(
										moduleVO.getModuleIdf()).append(
										"\" id=\"r").append(
										moduleVO.getModuleIdf()).append("\">")
								.append("&nbsp;").append(operation.getNamef())
								.append("&nbsp;");
					}
				}
				// Operation End
				if(resourceID.equals("-2") || resourceID.equals("-1")){
					output.append("</td><td class=\"td1\">&nbsp;");
				}else{
					output.append("</td><td class=\"td2\">&nbsp;");
				}
				 if(!"-1".equals(moduleVO.getModuleIdf())){
				output
						.append(
								"<input type=\"button\" name=\"querybtn\" value=\"修改\" class=\"sysbutton\" onclick=\"toUpdate('")
						.append(pagePath)
						.append("/sys/moduletoUpdate.action?fid=").append(
								moduleVO.getModuleIdf()).append("')\" />");
				
					String str = "";
					if(moduleVO.getStatusf().equals("0")){
						str = "启用";
					}else{
						str = "禁用";
					}
					
					//if(null!=superStr && superStr.equals("1")){
						output.append("&nbsp;&nbsp;<input type=\"button\" name=\"querybtn\" id=\'"+moduleVO.getModuleIdf()+"_button\' ")
						      .append(" value=\'"+str+"\' ")
						      .append(" class=\"sysbutton\" onclick=\"changeStatus('" )
							  .append(moduleVO.getModuleIdf())
						      .append("',this)\" />");
					//}
				}
				 
				output.append("</td>\n</tr>\n");
				if (isHasChildren) {
					position++;
					toViewWholeModuleOper(output, moduleVO.getModuleIdf(),pagePath);
					position--;
				}
			}
			trCss++;
		}
		//更新application里的菜单
		//Struts2Utils.getSession().getServletContext().setAttribute(WebConstants.WHOLEMENUTREE,this.toListNoPage());
		return output.toString();
	}

	private String echoSpace(int count) {
		StringBuffer output = new StringBuffer(20);
		for (int i = 0; i < count; i++) {
			output.append("&nbsp;&nbsp;");
		}
		return output.toString();
	}

	public List<BaseVo> toListNoPage() throws Exception {
		return (List<BaseVo>) getBaseDao().queryForList("toList",
				" order by " + WebConstants.DEFAULTORDERFIDS);
	}
	
	@SuppressWarnings("unchecked")
	public List<BaseVo> toListNoPageDwr(String parentidf) throws Exception {
		WebContext webContext = WebContextFactory.get();
		List<BaseVo> retVOList = new ArrayList<BaseVo>();
		List<ModuleVO> moduleVOList = (List<ModuleVO>)webContext.getServletContext().getAttribute(WebConstants.WHOLEMENUTREE);
		for (ModuleVO moduleVO : moduleVOList) {
			if(moduleVO.getParentIdf().equals(parentidf)){
				retVOList.add(moduleVO);
			}
		}
		return retVOList;
	}
	
	private String echoLine(int count) {
		StringBuffer output = new StringBuffer(20);
		for (int i = 0; i < count; i++) {
			output.append("<span style=\"font-size:6px\">.....</span>");
		}
		return output.toString();
	}

	private boolean isHasChildren(List<ModuleVO> moduleAndOperlist,
			String resourceID) throws Exception {
		for (int i = 0; i < moduleAndOperlist.size(); i++) {
			ModuleVO moduleVO = (ModuleVO) moduleAndOperlist.get(i);
			if (resourceID.equalsIgnoreCase(moduleVO.getParentIdf())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 用于处理数据删除的业务

	 * 
	 * @param cfg
	 * @return
	 */
	public String doDelete(String[] pks) throws Exception {
		if (pks != null && pks.length > 0) {
			this.getBaseDao().doDelete("doDelete", pks);// 删除模块记录
			moduleOperationDao.doDelete("doDelete", pks);// 删除操作记录
		}
		return ActionConstants.RELOAD;
	}

	public String isExistModuleIdAndOPerationId(String vomoduleIdf_new,
			String vomoduleIdf_old, String[] moduleOperation_new)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		if (((ModuleDao) this.getBaseDao()).isExistModuleIdf(vomoduleIdf_new,
				vomoduleIdf_old)) {
			sb.append("模板标识：").append(vomoduleIdf_new).append("已经存在！<br>");
		}
		StringBuilder sqlWhere = new StringBuilder(" where 1=1");
		if (!StringUtil.isNullorEmpty(vomoduleIdf_old)) {
			sqlWhere.append(" and moduleidf<>'").append(vomoduleIdf_old)
					.append("'");
		if (moduleOperation_new != null && moduleOperation_new.length > 0) {
			sqlWhere.append(" and operationIdf in(");
			for (int i = 0; i < moduleOperation_new.length; i++) {
				if (i != 0) {
					sqlWhere.append(",");
				}
				sqlWhere.append("'").append(moduleOperation_new[i]).append("'");
			}
			sqlWhere.append(")");
			List<BaseVo> moduleOperationVOlist = moduleOperationDao.queryForList(
					"toList", sqlWhere.toString());
			if (moduleOperationVOlist.size() > 0) {
				for (BaseVo vo : moduleOperationVOlist) {
					sb.append("操作标识：").append(
							((ModuleOperationVO) vo).getOperationIdf()).append(
							"已经存在！<br>");
				}
			}
		}
		}
		return sb.toString();
	}
	/* (non-Javadoc)
	 * @see com.framework.main.sys.module.service.ModuleService#getModuleOperationVOById(java.lang.String)
	 */
	public ModuleOperationVO getModuleOperationVOById(String operateId) throws Exception{
		return (ModuleOperationVO) this.getModuleOperationDao().getById("toView", operateId);
	}
	public ModuleOperationDao getModuleOperationDao() {
		return moduleOperationDao;
	}

	public void setModuleOperationDao(ModuleOperationDao moduleOperationDao) {
		this.moduleOperationDao = moduleOperationDao;
	}

	@Override
	public List<BaseVo> toGetNopageList() throws Exception {
		return (List<BaseVo>) getBaseDao().queryForList("toList"," where parentIdf='-1' order by datasortNumf asc ");
	}
	
	public int changeStatus(String moduleidf,String statusf) throws Exception {
		ModuleVO vo = new ModuleVO();
		vo.setModuleIdf(moduleidf);
		vo.setStatusf(statusf);
		return this.getBaseDao().doUpdate("doUpdateStatus", vo);
	}
}
